package com.ershijin.resourceserver.config;

import com.ershijin.common.config.OpaqueTokenProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@RequiredArgsConstructor
public class ResourceServerConfig {
    private final OpaqueTokenProperties opaqueTokenProperties;

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.mvcMatcher("/articles/**")
                .authorizeRequests()
                .mvcMatchers("/articles/**")
                .access("hasAuthority('USER')")
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .oauth2ResourceServer()
                .opaqueToken()
                .introspector(new CachingOpaqueTokenIntrospector(opaqueTokenProperties.getIntrospectionUri(), opaqueTokenProperties.getClientId(), opaqueTokenProperties.getClientSecret()));
        return http.build();
    }
}